const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');
const  existsSync = require('fs').existsSync;
const pkgPath = path.join( __dirname + "/package.json" );
// const pxtorem = 

const pkg = existsSync(pkgPath) ? require(pkgPath) : {};

let theme = {};
if (pkg.theme && typeof(pkg.theme) === 'string') {
    let cfgPath = pkg.theme;
    // relative path
    if (cfgPath.charAt(0) === '.') {
      cfgPath = path.resolve(__dirname, cfgPath);
    }
    
    const getThemeConfig = require(cfgPath);
    theme = getThemeConfig;
} else if (pkg.theme && typeof(pkg.theme) === 'object') {
    theme = pkg.theme;
}

// 判断生产&&测试环境
let isProduction = function() {
    return process.env.NODE_ENV ==='production';
};

const webpackconfig = {
	entry: {
		js: path.resolve('./app/client.js'),
		vendor: [
	      'react', 'classnames', 'react-router', 'react-dom'
	    ]
	},
	output: {
	    filename: '[name].js',
	    path: path.join(__dirname, 'dist'),
	    chunkFilename: '[name].js'
	},
	resolve: {
	    // modulesDirectories: ['node_modules', path.join(__dirname, '../node_modules')],
    	extensions: ['.web.js', '.jsx', '.js', '.json'],
	    alias: {
	      components: __dirname + '/app/components',
	      actions: __dirname + '/app/actions',
	      api: __dirname + '/app/api',
	      reducers: __dirname + '/app/reducers',
	      utils: __dirname + '/app/utils',
	      constants: __dirname + '/app/constants',
		  controllers: __dirname + '/app/controllers',
		  wxAjaxUtil: __dirname + '/app/common/wxajaxservice'
	    }
	},
	module:{
		loaders:[
			{
		        test: /\.js[x]?$/,
		        exclude: /node_modules/,
		        loader: 'react-hot-loader!babel-loader'
		    },
		    {
		      test: /\.css$/i,
			  // exclude: /node_modules/,
		      loader: 'style-loader!css-loader'
		  	},
		  	{ test: /\.(svg)$/i, loader: 'svg-sprite-loader', include: [
		        require.resolve('antd-mobile').replace(/warn\.js$/, ''),  // 1. 属于 antd-mobile 内置 svg 文件
		        path.resolve(__dirname, 'app/components/assets')  // 自己私人的 svg 存放目录
		    ]},
		    {
		       test: /\.less$/,
		       exclude: /node_modules/,
		       loader: 'style-loader!css-loader?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]!' + `less-loader?{"sourceMap":true,"modifyVars":${JSON.stringify(theme)}}`
		    },
		    {
		       test: /\.less$/,
		       include:/node_modules/,
		       loader: 'style-loader!css-loader!postcss-loader!' + `less-loader?{"sourceMap":true,"modifyVars":${JSON.stringify(theme)}}`
		    },
		    {
		        test: /\.(png|jpg)$/,
		        loader: 'url-loader?limit=8192'
		    }
		]
	},

	plugins:[
		// new webpack.DefinePlugin({
	 //     "process.env": { 
	 //         NODE_ENV: JSON.stringify("development")
	 //         // NODE_ENV: JSON.stringify("production") 
	 //       }
	 //    }),
		// new HtmlWebpackPlugin({
	 //      template: path.join(__dirname, 'app/index.html'),
	 //    }),
	    new OpenBrowserPlugin({
	      url: 'http://localhost:3008'
	    }),
	    // new webpack.optimize.UglifyJsPlugin({minimize: true}),
    	new webpack.optimize.CommonsChunkPlugin({name:'vendor', filename:'vendor.bundle.js'}),
        new webpack.LoaderOptionsPlugin({
            options: {
                postcss: function(){
                    return [
                        require("autoprefixer")({
                            browsers: ['ie>=8','>1% in CN']
                        },pxtorem({
                            rootValue: 100,
                            propWhiteList: [],
                        }))
                    ]
                }
            }
        })
  ],
	devtool: 'source-map',
	devServer: {
	    contentBase: './app/',
	    historyApiFallback: true,
	    hot: true,
	    disableHostCheck: true
	}
	// ,
	// externals: {
 //      'react': 'React',
 //      'react-dom':'ReactDOM'
 //    }
}

if( isProduction() ){
	webpackconfig.plugins.push(
		new webpack.DefinePlugin({
	     "process.env": { 
	         NODE_ENV: JSON.stringify("production") 
	       }
	    })
	);
	webpackconfig.plugins.push(
		new HtmlWebpackPlugin({
	      template: path.join(__dirname, 'app/index.html'),
	    })
	);
	webpackconfig.plugins.push(
		new webpack.optimize.UglifyJsPlugin({minimize: true})
	);
	webpackconfig.externals = {
							      'react': 'React',
							      'react-dom':'ReactDOM'
							  };
}else{
	webpackconfig.plugins.push(
		new webpack.DefinePlugin({
	     "process.env": { 
	         NODE_ENV: JSON.stringify("development") 
	       }
	    })
	);
	webpackconfig.plugins.push(
		new HtmlWebpackPlugin({
	      template: path.join(__dirname, 'app/index.dev.html'),
	    })
	);
}

module.exports = webpackconfig;